<template>
  <div class="chartarea">
    <div id="energyBarchart" class="echart"></div>
  </div>
</template>

<script>
import echarts from "@/utils/lib/echarts";
import { BarChart } from "echarts/charts";
echarts.use([BarChart]);
export default {
  name: "energyBarchart",
  props: {
    // 图数据
    chartData: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  mounted() {
    this.getChartsdata(this.chartData);
  },
  beforeDestroy() {
    this.chartDes();
  },
  watch: {
    chartData: {
      handler(val) {
        if (val) {
          this.chartDes();
          this.getChartsdata(this.chartData);
        }
      },
      deep: false,
      immediate: false,
    },
  },
  methods: {
    chartDes() {
      if (!this.chart) {
        return;
      }
      this.chart.dispose();
      this.chart = null;
    },
    getChartsdata(chartData) {
      let option = {
        // title: {
        //   text: ''
        // },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        legend: {
          // orient: "vertical",
          bottom: "0%",
          padding: 0,
          // right: "0%",
          // icon: 'circle',
          itemGap: 3,
          textStyle: {
            color: "#8C8C8C",
            fontFamily: "PingFang-SC-Regular, PingFang-SC",
            fontWeight: 400,
            lineHeight: 17,
          },
        },
        tooltip: {
          valueFormatter: function (value) {
            return value + " 条";
          },
        },
        grid: {
          left: "0%",
          right: "5%",
          top: "5%",
          bottom: "20%",
          containLabel: true,
        },
        xAxis: {
          type: "value",
          name: "条",
          boundaryGap: [0, 0.01],
        },
        yAxis: {
          type: "category",
          data: chartData.yAxisData,
        },
        series: chartData.seriesData,
      };
      this.initChart("energyBarchart", option);
    },
    initChart(id, options) {
      this.chart = echarts.init(document.getElementById(id));
      this.chart.setOption(options);
      window.addEventListener("resize", () => {
        if (this.chart) {
          this.chart.resize();
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.chartarea {
  .echart {
    width: 100%;
    height: 240px;
  }
}
</style>
